/* eslint-disable no-unused-expressions */
/*
 * @Author: AskMeWhy
 * @Date:   2020-05-12 16:56:25
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-01-13 18:06:53
 */
const CosAuth = require("../libs/cos-auth");
// 计算签名
const getAuthorization = function (options, callback, errCallBack) {
    getCredentials(
        options.initAuth,
        function (credentials) {
            console.log("-----------计算签名-----------")
            console.log(credentials)
            console.log("-----------计算签名-----------")
            callback({
                XCosSecurityToken: credentials.sessionToken,
                Authorization: CosAuth({
                    SecretId: credentials.tmpSecretId,
                    SecretKey: credentials.tmpSecretKey,
                    Method: options.Method,
                    Pathname: options.Pathname,
                }),
            });
        },
        errCallBack
    );
};
// 获取临时密钥
let stsCache;
const getCredentials = function (initAuth, callback, errCallBack) {
    if (stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
        callback(stsCache.credentials);
        return;
    }
    if (initAuth) {
        initAuth()
            .then(r => {
                stsCache = r;
                callback(stsCache.credentials);
            })
            .catch(err => {
                console.log(err);
                errCallBack(err);
                // wx.showModal({ title: "错误提示", content: "临时密钥获取失败", showCancel: false });
            });
    } else {
        errCallBack({ title: "错误提示", content: "临时密钥获取失败" });
        // wx.showModal({ title: "错误提示", content: "临时密钥获取失败", showCancel: false });
    }
};
const wxUploadFile = (curFile, option, files, type = "file") => {

    const _suffix = curFile.filePath.substring(curFile.filePath.lastIndexOf("."));
    const uploadFileName = curFile.dir + +new Date() + Math.floor(Math.random() * 150) + _suffix;
    const uploadServerURL = option.action; // OSS地址，需要https

    console.log("----上传的option参数-------")
    console.log(option);
    console.log(uploadFileName);
    console.log(curFile);
    console.log("----上传的option参数-------")


    const resData = {
        ...curFile,
        status: "uploading",
        url: uploadServerURL,
        fileName: uploadFileName,
    };
    if (type === "cover") {
        resData.coverFileName = uploadFileName;
    }
    return new Promise(resolve => {
        if (resData.size > option.limit) {
            resData.status = "fail";
            option.afterUpload && option.afterUpload(resData, files, ["limit"], type);
            resolve(resData);
            return;
        }
        option.beforeUpload && option.beforeUpload(resData, files, [], type);
        getAuthorization(
            { initAuth: option.initAuth, Method: "POST", Pathname: "/" },
            function (AuthData) {
                
                wx.uploadFile({
                    url: uploadServerURL, // 开发者服务器 url
                    filePath: curFile.filePath, // 要上传文件资源的路径
                    name: "file", // 必须填file
                    formData: {
                        key: uploadFileName,
                        success_action_status: 200,
                        Signature: AuthData.Authorization,
                        "x-cos-security-token": AuthData.XCosSecurityToken,
                        "Content-Type": "",
                    },
                    success(res) {
                        if (res.statusCode !== 200) {
                            resData.status = "fail";
                            option.afterUpload && option.afterUpload(resData, files, [], type);
                            resolve(resData);
                            return;
                        }
                        resData.src = uploadServerURL + "/" + uploadFileName;
                        resData.status = "success";
                        option.afterUpload && option.afterUpload(resData, files, [], type);
                        resolve(resData);
                    },
                    fail(err) {
                        console.log("err", err);
                        resData.status = "fail";
                        option.afterUpload && option.afterUpload(resData, files, [], type);
                        resolve(resData);
                    },
                });
            },
            function (err) {
                console.log("err", err, resData);
                resData.status = "fail";
                option.afterUpload && option.afterUpload(resData, files, [], type);
                resolve(resData);
            }
        );
    });
};

const _uploadFile = async (files, index = 0, option) => {

    let res = [];
    if (files.length === 0) {
        return res;
    }
    if (files[index].type === "cover" && !option.disabledCover) {
        const responseCover = await wxUploadFile(
            {
                ...files[index],
                filePath: files[index].cover,
            },
            option,
            files,
            files[index].type
        );
        if (responseCover.status === "fail") {
            files[index].status = "fail";
            option.afterUpload && option.afterUpload(files[index], files, []);
            return res;
        }
    }
    const response = await wxUploadFile(files[index], option, files);
    res.push(response);
    index++;
    if (index <= files.length - 1) {
        const _r = await _uploadFile(files, index, option);
        res = res.concat(_r);
    }
    return res;
};

export const uploadFile = async (files, option = {}) => {


    files = files.map(cur => ({
        ...cur,
        status: "pending",
    }));
    option.onReady && option.onReady(files);
    
    const res = await _uploadFile(files, 0, option);
    return res;
};
